package cn.ac.iscas.focuscrawler;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.ac.iscas.algorithm.Similarity;
import cn.ac.iscas.webpage.extraction.KeywordsExtractor;

/**
 * @author peterstone
 * 
 */
public class RelativeBuilder {

	Map<String, Double> queryVector = new HashMap<String, Double>();
	private final static double relevantThreshold = 0.003;

	public static double getRelevantThreshold() {
		return relevantThreshold;
	}

	public RelativeBuilder(String keywords) {
		String[] tempStringArray = keywords.split(" ");
		for (int i = 0; i < tempStringArray.length; i++) {
			String s = tempStringArray[i];
			if (queryVector.containsKey(s)) {
				queryVector.put(s, queryVector.get(s) + 1);
			} else {
				queryVector.put(s, 1.0);
			}
		}
	}

	public Double getRelativeWeight(String html) {
		Double result = 0.0;
		try {
			Map<String, Double> docVector = (new KeywordsExtractor()).getKeyWords(html);
			result = (new Similarity()).getSimilariy(queryVector, docVector);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 
	 * @param html
	 * @param alpha  the factor of influence on doc vector. A negative number means a irrelevant document.
	 */
	public void refineQueryVector(String html, Double alpha) {
		try {
			Map<String, Double> docVector = (new KeywordsExtractor()).getKeyWords(html);
			Set<String> keySet = docVector.keySet();
			for(String s : keySet) {
				if (queryVector.containsKey(s)) {
					queryVector.put(s, alpha * docVector.get(s) + queryVector.get(s));
				} else {
					queryVector.put(s, alpha * docVector.get(s));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
